from flask import Blueprint, jsonify, request
from file_manager import FileManager, PreviewManager, CleanupManager
from task_manager import TaskManager
from video_processor import VideoBackgroundReplacer
from config import Config
from datetime import datetime
import psutil
import os
import sys
from utils.logger import get_logger

logger = get_logger(__name__)


def create_system_routes(file_manager: FileManager, preview_manager: PreviewManager,
                         task_manager: TaskManager):
    """创建系统相关路由"""

    system_bp = Blueprint('system', __name__)

    @system_bp.route('/health', methods=['GET'])
    def health_check():
        """健康检查"""
        try:
            replacer = VideoBackgroundReplacer('health')

            # 基础健康状态
            health_status = {
                'status': 'healthy',
                'timestamp': datetime.now().isoformat(),
                'version': '2.0.0',
                'uptime': _get_uptime()
            }

            # 系统依赖检查
            health_status['dependencies'] = {
                'ffmpeg_available': replacer.check_ffmpeg(),
                'ffprobe_available': replacer.check_ffprobe(),
                'pil_available': _check_pil()
            }

            # 服务状态
            health_status['services'] = {
                'active_tasks': task_manager.get_active_tasks_count(),
                'active_previews': len(preview_manager.active_previews),
                'database_accessible': _check_database()
            }

            # 判断整体健康状态
            if not all(health_status['dependencies'].values()):
                health_status['status'] = 'degraded'

            return jsonify(health_status)

        except Exception as e:
            logger.error(f"健康检查失败: {e}")
            return jsonify({
                'status': 'unhealthy',
                'timestamp': datetime.now().isoformat(),
                'error': str(e)
            }), 500

    @system_bp.route('/info', methods=['GET'])
    def get_system_info():
        """获取系统信息"""
        try:
            info = {
                'application': {
                    'name': '数字人视频背景替换系统',
                    'version': '2.0.0',
                    'author': 'AI Assistant',
                    'description': '采用模块化架构'
                }
            }

            return jsonify({
                'success': True,
                'info': info
            })

        except Exception as e:
            logger.error(f"获取系统信息失败: {e}")
            return jsonify({'success': False, 'message': '获取系统信息失败'}), 500

    @system_bp.route('/cleanup', methods=['POST'])
    def manual_cleanup():
        """手动清理资源"""
        try:
            data = request.get_json() or {}
            cleanup_type = data.get('type', 'all')

            # 解析清理类型（支持逗号分隔的多个类型）
            if cleanup_type == 'all':
                cleanup_types = ['previews', 'temp', 'output', 'tasks']
            else:
                # 将逗号分隔的字符串转换为列表
                cleanup_types = [t.strip() for t in cleanup_type.split(',')]

            logger.info(f"执行清理操作，类型: {cleanup_types}")

            results = {}

            if 'previews' in cleanup_types:
                # 获取自定义的保留时间，如果没有则使用默认值
                preview_hours = data.get('preview_retention_hours', Config.PREVIEW_RETENTION_HOURS)
                results['previews'] = preview_manager.cleanup_old_previews(preview_hours)
                logger.info(f"预览清理结果: {results['previews']} 个文件")

            if 'temp' in cleanup_types:
                # 获取自定义的保留时间，如果没有则使用默认值
                temp_hours = data.get('temp_retention_hours', Config.TEMP_RETENTION_HOURS)
                results['temp_files'] = CleanupManager.cleanup_temp_files(temp_hours)
                logger.info(f"临时文件清理结果: {results['temp_files']} 个目录")

            if 'output' in cleanup_types:
                days = data.get('output_retention_days', 7)
                results['output_files'] = CleanupManager.cleanup_output_files(days)
                logger.info(f"输出文件清理结果: {results['output_files']} 个文件")

            if 'tasks' in cleanup_types:
                hours = data.get('task_retention_hours', 24)
                results['completed_tasks'] = task_manager.cleanup_completed_tasks(hours)
                logger.info(f"任务记录清理结果: {results['completed_tasks']} 个任务")

            total_cleaned = sum(results.values())

            logger.info(f"清理完成，总共清理了 {total_cleaned} 个项目，详情: {results}")

            return jsonify({
                'success': True,
                'message': f'清理完成，总共清理了 {total_cleaned} 个项目',
                'details': results
            })

        except Exception as e:
            logger.error(f"手动清理失败: {e}", exc_info=True)
            return jsonify({'success': False, 'message': f'清理失败: {str(e)}'}), 500

    # 私有辅助函数
    def _get_uptime():
        """获取系统运行时间"""
        try:
            import time
            uptime_seconds = time.time() - psutil.boot_time()
            return f"{uptime_seconds:.0f} seconds"
        except:
            return "unknown"

    def _check_pil():
        """检查PIL是否可用"""
        try:
            from PIL import Image
            return True
        except ImportError:
            return False

    def _check_database():
        """检查数据库是否可访问"""
        try:
            from flask import current_app
            with current_app.task_dao.db.get_connection() as conn:
                conn.execute('SELECT 1').fetchone()
            return True
        except:
            return False

    return system_bp